﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using GroundWater.Data;
using GroundWater.BusinessActions;

using MonitoringTable = GroundWater.Data.MonitoringDataSet.MonitoringDataTable;
using MonitoringRow = GroundWater.Data.MonitoringDataSet.MonitoringRow;

namespace GroundWater.waterlevel
{
    public partial class WaterLevelWarning : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "水位检查");
            if (!this.IsPostBack)
            {
                txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

                //string startDate = DateTime.Now.ToString("yyyy-MM-dd");
                //string endDate = DateTime.Now.ToString("yyyy-MM-dd");
                //txtMax.Text = System.Configuration.ConfigurationManager.AppSettings["MaximumWaterlevel"];
                //txtMin.Text = System.Configuration.ConfigurationManager.AppSettings["MinimumWaterlevel"];

                btnCheck_Click(null, EventArgs.Empty);
            }
        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }
        }

        protected void btnCheck_Click(object sender, EventArgs e)
        {
            #region validate

            //if (!Husb.Util.CommonUtil.IsNumber(txtMax.Text))
            //{
            //    lblEmpty.Text = "<br />最高水位警戒水位为数值！";
            //    lblEmpty.Visible = true;
            //    return;
            //}

            //if (!Husb.Util.CommonUtil.IsNumber(txtMin.Text))
            //{
            //    lblEmpty.Text = "<br />最低水位警戒水位为数值！";
            //    lblEmpty.Visible = true;
            //    return;
            //}

            if (txtStartDate.Text.Length < 6)
            {
                txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (txtEndDate.Text.Length < 6)
            {
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }

            DateTime endDate1;
            DateTime startDate1;


            if (!DateTime.TryParse(txtStartDate.Text, out startDate1) || !DateTime.TryParse(txtEndDate.Text, out endDate1))
            {
                return;
            }
            #endregion

            string startDate = txtStartDate.Text;
            string endDate = txtEndDate.Text;

            //if (txtMax.Text.Length == 0)
            //{
            //    txtMax.Text = System.Configuration.ConfigurationManager.AppSettings["MaximumWaterlevel"];
            //}
            //if (txtMin.Text.Length == 0)
            //{
            //    txtMin.Text = System.Configuration.ConfigurationManager.AppSettings["MinimumWaterlevel"];
            //}

            //MonitoringTable dt = Monitoring.FetchWaterlevelWarning(startDate, endDate, Convert.ToDecimal(txtMin.Text), Convert.ToDecimal(txtMax.Text));

            MonitoringTable dt = Monitoring.CheckWaterlevel(startDate, endDate, drpType.SelectedIndex == 1);

            //DataTable dt = Monitoring.FetchWaterLeveByDate("2009-05-10", "2009-05-15");

            if (dt == null || dt.Rows.Count == 0)
            {
                //lblEmpty.Text = "<br />您所选定的时间段内，按最高水位" + txtMax.Text + "和最低水位" + txtMin.Text + " 来检查，无异常水位信息！";
                lblEmpty.Text = "<br />您所选定的时间段内，无异常水位信息！";
                lblEmpty.Visible = true;
            }
            else
            {
                gvWarning.Columns[4].HeaderText = drpType.SelectedIndex == 1 ? "最低警戒水位" : "最高警戒水位";
                (gvWarning.Columns[4] as BoundField).DataField = drpType.SelectedIndex == 1 ? "MinimumWaterlevel" : "MaximumWaterlevel";
                gvWarning.DataSource = dt;
                gvWarning.DataBind();

                lblEmpty.Visible = false;
            }
        }


        protected void btnExport_Click(object sender, EventArgs e)
        {
            //MonitoringTable dt = Monitoring.FetchByDatePaged(txtStartDate.Text, txtEndDate.Text, "", 1000000, 0);
            MonitoringTable dt = Monitoring.CheckWaterlevel(txtStartDate.Text, txtEndDate.Text, drpType.SelectedIndex == 1);
            ExportToExcel("水位告警.xls", dt, gvWarning);
        }

        public void ExportToExcel(string fileName, MonitoringTable dt, GridView gv)
        {
            this.Page.Response.Clear();
            this.Page.Response.Buffer = true;
            this.Page.Response.AddHeader("Content-type", "application/x-msdownload");
            this.Page.Response.ContentType = "application/vnd.ms-excel";
            this.Page.Response.Charset = "utf-8";
            this.Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
            this.EnableViewState = false;

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            GridView grid = new GridView();

            grid.RowDataBound += new GridViewRowEventHandler(gvExport_RowDataBound);
            grid.DataSource = dt;
            grid.AutoGenerateColumns = false;
            grid.Columns.Clear();
            foreach (DataControlField col in gv.Columns)
            {
                if (col is ButtonField || col is CommandField)
                {
                    continue;
                }
                if (col is BoundField || col is TemplateField || col is CheckBoxField)
                {
                    grid.Columns.Add(col);
                }
                if (col is HyperLinkField)
                {
                    BoundField field = new BoundField();
                    field.DataField = ((HyperLinkField)col).DataTextField;
                    field.HeaderText = col.HeaderText;
                    grid.Columns.Add(field);
                }
            }

            grid.DataBind();
            grid.RenderControl(htw);

            this.Page.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            this.Page.Response.Write(@"<style> .text { mso-number-format:\@; } </style> "); ;
            //string fileName = HttpUtility.UrlEncode(ExcelFileName + ".xls", Encoding.GetEncoding("GB2312"));
            //HttpContext.Current.Response.AddHeader("content-disposition","attachment;filename=" + fileName);
            this.Page.Response.Write(sw.ToString());
            this.Page.Response.End();
        }

        protected void gvExport_RowDataBound(object sender, GridViewRowEventArgs args)
        {
            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                args.Row.Cells[0].Attributes.Add("class", "text");
            }
        }
    }
}
